﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using ADministration.Web;
using System.ServiceModel.DomainServices.Client;

namespace ADministration.Views
{
    public partial class Categories : Page
    {
        public Categories()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void categoryDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void buttonRelaod_Click(object sender, RoutedEventArgs e)
        {
            this.categoryDomainDataSource.Clear();
            this.categoryDomainDataSource.Load();
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/CategoriesViews/AddCategory", UriKind.Relative));
        }

        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            Category selectedCategory = this.categoryDataGrid.SelectedItem as Category;
            if (selectedCategory != null)
            {
                string editCategoryUri = string.Format("/CategoriesViews/DeleteCategory?id={0}",
                    selectedCategory.CategoryID);
                NavigationService.Navigate(new Uri(editCategoryUri, UriKind.Relative));
            }
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            this.categoryDomainDataSource.SubmitChanges();
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            string categoryName = this.textBoxSearchName.Text;
            if (categoryName != string.Empty)
            {
                TicketsDomainContext context = new TicketsDomainContext();
                this.categoryDataGrid.ItemsSource = context.Categories;

                EntityQuery<Category> query = context.GetCategoriesByNameQuery(categoryName);
                LoadOperation<Category> loadOp = context.Load(query);
            }
            else
            {
                this.categoryDataGrid.ItemsSource = this.categoryDomainDataSource.Data;
            }
        }
    }
}
